package crons;

import helpers.DateHelper;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import admin.models.AutoSiteModel;


import entities.AutoSite;


public class CronAutoSiteLastestArticle extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(CronAutoSiteLastestArticle.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		log.setLevel(Level.FINE);
		response.setContentType("text/plain");
		
		AutoSiteModel autoSiteModel = AutoSiteModel.getInstance();
		List<AutoSite> sites = autoSiteModel.getAll();
		for (int i = 0; i < sites.size(); i++) {
			AutoSite site = sites.get(i);
			if (!DateHelper.checkGreaterNow(site.getLastestScheduleSite(), site.getScheduleSite()) && site.getStatus() == 1) {
			//if (site.getStatus() == 1) {
				Queue queue = QueueFactory.getDefaultQueue();
				String queueUrl = "/queue-lastest-article/" + site.getId();
				queue.add(TaskOptions.Builder.withUrl(queueUrl).method(Method.GET));
				log.info(queueUrl);
				response.getWriter().println("Cron lastest article success autoSite id: " + site.getId());
			} else {
				response.getWriter().println("Cron lastest article unsuccess autoSite id: " + site.getId());
			}
		}
	}
}
